package com.wo.cloud.security;

import cn.hutool.core.util.StrUtil;
import com.wo.cloud.util.Response;
import com.wo.cloud.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/18 23:03
 * Description: 退出处理器
 */
public class TokenLogoutHandler implements LogoutHandler {

    private RedisTemplate redisTemplate;
    private TokenManager tokenManager;

    @Autowired
    public TokenLogoutHandler(RedisTemplate redisTemplate,
                              TokenManager tokenManager){
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // 从header 中获取token
        String token = request.getHeader("token");

        // 判断token 是否为空
        if (StrUtil.isNotBlank(token)) {
            // 获取用户信息
            String userInfoByToken = tokenManager.getUserInfoByToken(token);

            // 根据用户名从token中删除token
            redisTemplate.delete(userInfoByToken);
        }

        ResponseUtil.out(response, Response.data("退出成功过"));


    }
}
